package com.fanhang.samples.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionProvider {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private static ConnectionProvider instance;
	private Connection connection = null;
	private String driverClass = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://192.168.5.4:3306/jnode";
	private String userName = "fanhang";
	private String passWord = "hh";
	

	private ConnectionProvider() throws Exception {
		init();
	}

	private void init() throws Exception {
		logger.info("init driver class: " + this.driverClass);
		logger.info("init url         : " + this.url);
		Class.forName(driverClass);
		connection = DriverManager.getConnection(this.url, this.userName, this.passWord);
	}

	public static ConnectionProvider getInstance() {
		try {
			if (instance == null) {
				instance = new ConnectionProvider();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return instance;
	}

	public Connection getConnection() throws Exception {
		if (!this.connection.isClosed()) {
			this.closeConnection();
		}
		connection = DriverManager.getConnection(this.url, this.userName, this.passWord);
		return connection;
	}

	public void closeConnection() {
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void rollback() throws Exception {
		if (connection != null) {
			connection.rollback();
		}
	}

}
